/* eslint-disable @typescript-eslint/no-explicit-any */
import { message } from 'antd'
import axios, { AxiosError } from 'axios'
// import { showLoading } from './loading/index.tsx'
import storage from './storage'
import { Result } from '../types/api'
import { showLoading, hideLoading } from './loading/index'
const instance = axios.create({
  //   baseURL: import.meta.env.VITE_BASE_API,
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 8000,
  timeoutErrorMessage: '请求超时，请稍后再试',
  withCredentials: false
})

// console.log(import.meta.env.VITE_BASE_API)
// showLoading()
//请求拦截器
instance.interceptors.request.use(
  config => {
    showLoading()
    const token = storage.get('token')
    if (token) {
      config.headers.Authorization = 'Bearer ' + token
    }
    config.headers.icode = '6AC72278E61172EE'
    // console.log('config', config, 'token', token)
    return {
      ...config
    }
  },
  (error: AxiosError) => {
    console.log(error)

    return Promise.reject(error)
  }
)
//响应拦截器
instance.interceptors.response.use(
  response => {
    console.log('response:', response)
    hideLoading()
    const data: Result = response.data
    if (response.config.responseType === 'blob') return response
    if (data.code === 50001) {
      message.error(data.msg)
      storage.remove('token')
      location.href = '/login?callback=' + encodeURIComponent(location.href)
    } else if (data.code != 0) {
      message.error(data.msg)
      return Promise.reject(data)
    }
    return data.data
  },
  error => {
    message.error(error.message)
    return Promise.reject(error.message)
  }
)

export default {
  get<T>(url: string, params?: object): Promise<T> {
    return instance.get(url, { params })
  },
  post<T>(url: string, params: object): Promise<T> {
    return instance.post(url, params)
  },
  downloadFile(url: string, data: any, fileName = 'fileName.xlsx') {
    instance({
      url,
      data,
      method: 'post',
      responseType: 'blob'
    }).then(response => {
      const blob = new Blob([response.data], {
        type: response.data.type
      })
      const name = (response.headers['file-name'] as string) || fileName
      const link = document.createElement('a')
      link.download = name
      link.href = URL.createObjectURL(blob)
      document.body.append(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(link.href)
    })
  }
}
